module TunecoreDirect

  # This class includes all the methods that you have to interact with the TuneCore web service.  
  class TunecoreDirect::Request < TunecoreDirect::Base
    include TunecoreDirect
  
    # Creates a new account at Tunecore
    def create_person(email, password, name, phone_number, country, postal_code=nil)
      parameters = {  "email" => email,
                      "password" => password,
                      "name" => name,
                      "phone_number" => phone_number,
                      "country" => country,
                      "postal_code" => postal_code }
                    
      http_res = http_post("create_person", parameters )
      tc_res = Response.new( http_res.body )
      return tc_res
    end
    
    # Creates this new Album at TuneCore
    def create_album( params={} )
      http_res = http_post("create_album", params )
      tc_res = Response.new( http_res.body )
      return tc_res
    end
    
    # Creates this new Song at TuneCore
    def create_song( params={} )
      http_res = http_post("create_song", params )
      tc_res = Response.new( http_res.body )
      return tc_res
    end
    
    # Returns Response that will contain an #Album
    def get_album(album_id)
      params = { "album_id" => album_id }
      http_res = http_post("get_album", params )
      tc_res = Response.new( http_res.body )
      return tc_res
    end
    
    # Returns a Response that will contain many #Album objects
    def get_albums(person_id=nil)
      params = { "person_id" => person_id }
      http_res = http_post("get_albums", params )
      tc_res = Response.new( http_res.body ) 
      return tc_res
    end
        
    # Returns a #Person object for the given id
    def get_person(person_id)
      parameters = {"person_id" => person_id}
      http_res = http_post("get_person", parameters )
      tc_res = Response.new( http_res.body )
      return tc_res
    end
  
    # Returns an array of #Person objects associated with the current API key.
    def get_people
      http_res = http_post("get_people", Hash.new )
      tc_res = Response.new( http_res.body )
      return tc_res
    end
    
    # Sends a takedown request for this album
    def takedown_album(album_id)
      params = {"album_id" => album_id}
      http_res = http_post("takedown_album", params )
      tc_res = Response.new( http_res.body )
      return tc_res
    end
    
    private
  
    # Make contact with TC.  API key is inserted here automatically and is used to authenticate and authorize the request.
    def http_post(action, parameters={})
      raise "API key is not set" if @@api_key.nil?
      uri = URI.parse("#{@@tunecore_server}/partner/#{action}")
      parameters["api_key"] = @@api_key
      res = Net::HTTP.post_form(uri, parameters)
      raise "API key not authorized" if res.class == Net::HTTPForbidden
      return res
    end
  
  end
end